/**  
 * All rights Reserved, Designed By www.flksh.com
 * @date:   2017-10-30 15:33:40   
 * @Copyright: 2013-2017 www.flksh.com Inc. All rights reserved. 
 * 注意：本内容仅限于上海福乐康社区养老服务有限公司内部传阅，禁止外泄以及用于其他的商业目
 */
package com.zx.cloud.service;

import java.io.UnsupportedEncodingException;
import java.math.BigDecimal;
import java.net.URLEncoder;
import java.text.SimpleDateFormat;
import java.time.OffsetDateTime;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Random;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.zx.cloud.Shift;
import com.zx.cloud.controller.StatusCode;
import com.zx.cloud.domain.ClientInfo;
import com.zx.cloud.domain.ClientLoanOrder;
import com.zx.cloud.domain.Dict;
import com.zx.cloud.domain.LoanOrder;
import com.zx.cloud.domain.RepayDetail;
import com.zx.cloud.domain.RepayOrder;
import com.zx.cloud.persistence.ClientInfoMapper;
import com.zx.cloud.persistence.CrudMapper;
import com.zx.cloud.persistence.DictMapper;
import com.zx.cloud.persistence.LoanOrderMapper;
import com.zx.cloud.persistence.OrderLogMapper;
import com.zx.cloud.persistence.RepayDetailMapper;
import com.zx.cloud.persistence.RepayOrderMapper;
import com.zx.cloud.persistence.UserMapper;
import com.zx.cloud.util.OrderNoUtil;
import com.zx.cloud.util.Page;
import com.zx.cloud.util.SmsCodeUtil;

/**
 * 借款订单表
 */
@SpringBootApplication
@Transactional
@Service
public class LoanOrderService extends CrudServiceImpl<LoanOrder> {
	static final SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyyMMddHHmmssSSS");
	private static final Logger LOGGER = LoggerFactory.getLogger(LoanOrderService.class);

	@Autowired
	private LoanOrderMapper loanOrderMapper;
	@Autowired
	private RepayOrderMapper repayOrderMapper;
	@Autowired
	private UserMapper userMapper;
	@Autowired
	private OrderLogMapper orderLogMapper;
	@Autowired
	private OrderLogService orderLogService;
	@Autowired
	private DictMapper dictMapper;
	@Autowired
	private RepayDetailMapper repayDetailMapper;
	@Autowired
	private PayForService payForService;
	
	@Autowired
	private RepayOrderService repayOrderService;
	
    @Autowired
    private ClientInfoMapper clientInfoMapper;
	   
	@Autowired
	private FaceContrastService  faceContrastService;
	@Autowired
	private DictService dictService;
	
	@Autowired
	private  ClientRiskService  clientRiskService;
	
	@Value("${spring.profiles.active}")
	private String active;
	
 
	
	@Autowired
	public LoanOrderService(CrudMapper<LoanOrder> mapper) {
		super(mapper);
	}
	/**
	 * @Description:借款管理-借款订单列表
	 * @author likun
	 * @Create Time: 2017年10月31日上午10:35:43
	 */
	@Override
	public Page<LoanOrder> page(LoanOrder entity) {
		long count = loanOrderMapper.getLoanOrderCount(entity);
		Page<LoanOrder> page = new Page<LoanOrder>(entity.getPageIndex_(), entity.getPageSize_());
		page.setData(loanOrderMapper.getLoanOrderList(entity));
		page.setTotalCount(count);
		return page;
	}

	/**
	 * @Description:借款管理-创建借款订单
	 * @author likun
	 * @Create Time: 2017年10月31日上午10:35:43
	 */
	@Override
	public int insert(LoanOrder entity) {
	    new Thread() {
	           public void run() {
	        	   synchronized (LOGGER) {
	        		   LoanOrder  newLoanOrder=new LoanOrder();
	        			//根据会员，选择正常利息利率0.0005、征信服务费利率0.0095、逾期利率0.015,后期维护到会员的映射关系中
	        			Long clientId=entity.getClientId();
	        			Map<String, Object> params = new HashMap<String, Object>();
        				params.put("clientId", clientId);
        				List<LoanOrder>  loanOrders=getLoanOrderByClientId(params);
        				if(loanOrders.size()>0){
        					 Shift.fatal(StatusCode.NVALID_ORDER_LOAN,"还有正在处理的借款订单！");	
        				}
        				//被拒后40天才能申请
        				List<LoanOrder>  refuseLoanOrders=getRefuseLoanOrderByClientId(params);
        				if(refuseLoanOrders.size()>0){
        					 Shift.fatal(StatusCode.NVALID_ORDER_LOAN,"还有正在处理的借款订单！");	
        				}
        				List<RepayOrder> repayOrders=repayOrderService.getUnclearedOrderByClientId(params);
        				if(repayOrders.size()>0){
        					 Shift.fatal(StatusCode.INVALID_ORDER_REPAY,"还有未结清的借款订单！");	
        				}
	        			/**风控校验*/
	        			ClientInfo  clientInfo=clientRiskService.getClientInfo(clientId);
	        			if(clientInfo.getType() == 0){
	        				 Shift.fatal(StatusCode.INVALID_ORDER,"你尚未符合申请条件！");	
	        			}
	        			/**风控校验---18岁拒绝申请*/
	        			if(clientInfo.getAge() <=18){
	        				 Shift.fatal(StatusCode.INVALID_ORDER,"你尚未符合申请条件！");	
	        			}
	        			/**风控校验---40岁拒绝申请*/
	        			if(clientInfo.getAge() >40){
	        				 Shift.fatal(StatusCode.INVALID_ORDER,"你尚未符合申请条件！");	
	        			}
	        			/**风控校验---通讯录少于15拒绝申请*/
	        			int length=clientRiskService.getClientContactLength(clientId);
	        			if(length < 15){
	        				 Shift.fatal(StatusCode.INVALID_ORDER,"你尚未符合申请条件！");	
	        			}
	        		    ClientLoanOrder  cLoanOrder=clientRiskService.getClientLoanOrder(clientId);
	        		    LOGGER.info("******************************此会员风控给出的借款信息："+cLoanOrder.toString()+"********************************");
	        		    //借款利率
	                     BigDecimal  interestRate=cLoanOrder.getInterestRate();
	        			 newLoanOrder.setInterestRate(interestRate);
	        			 //服务费利率
	        			 BigDecimal  serviceRate=cLoanOrder.getServiceRate();
	        			 newLoanOrder.setServiceRate(serviceRate);
	        			 //逾期利率
	        			 BigDecimal  overdueRate=cLoanOrder.getOverdueRate();
	        			 newLoanOrder.setOverdueRate(overdueRate);
	        			//借款金额
	        			 BigDecimal loanAmount=cLoanOrder.getLoanAmount();
	        			 newLoanOrder.setLoanAmount(loanAmount);
                        //借款期限
	        			 int  loanTerm=cLoanOrder.getLoanTerm();
	        			 newLoanOrder.setLoanTerm(loanTerm);
	        			//正常利息
	        	        BigDecimal  repayInterest=cLoanOrder.getLoanInterest();
	        	        newLoanOrder.setRepayInterest(repayInterest);
	        			//征信服务费
	        			BigDecimal serviceCharge=cLoanOrder.getServiceCharge();
	        			newLoanOrder.setServiceCharge(serviceCharge);
	        			 //费用总和
	        			BigDecimal  feeTotal=cLoanOrder.getFeeTotal();
	        			newLoanOrder.setFeeTotal(feeTotal);//贷款服务费总和
	        			//到账金额
	        			BigDecimal  actualAmount=cLoanOrder.getActualAmount();
	        			newLoanOrder.setActualAmount(actualAmount);
	        			
	        			newLoanOrder.setClientId(clientId);
	        			newLoanOrder.setOrderNo("3"+OrderNoUtil.getSerialNumber());//订单编号
	        			newLoanOrder.setLivingPic(entity.getLivingPic());//活体识别
	        			newLoanOrder.setCreateTime(OffsetDateTime.now());//创建时间
	        			newLoanOrder.setStatus(0);//初始状态	
	        			/**电核人员分配*/
	        			try {
	        				newLoanOrder.setVerifyCode(getVerifyCode());
						} catch (Exception e) {
							LOGGER.info("******************************电核人员分配异常："+e.toString()+"********************************");
						}
	        			/**人脸比对*/
	        			try {
	        				String historical_selfie_url=clientInfo.getFrontImg();
	        				String  selfie_url=entity.getLivingPic().split(",")[0];
	        				boolean  flag=faceContrastService.HttpClientPost(historical_selfie_url, selfie_url);
	        				if(!flag){
	        					newLoanOrder.setStatus(1);//拒绝
	        				}
	        			} catch (Exception e) {
	        				LOGGER.info("******************************人脸比对异常："+e.toString()+"********************************");
	        			}
	        			mapper.insert(newLoanOrder);
	        				
	        	   }
	             }
	           }.start();
	           return  1;
		
	}
	/**
	 * @Description:生成随机电核人员
	 */
	private  String getVerifyCode(){
		Dict dict=new Dict();
		dict.setParentCode("VC0001");
		List<Dict> dicts=dictMapper.getDitByParentCode(dict);
		int max=dicts.size();
		int min=0;
	    Random random = new Random();
	    int checkIndex = random.nextInt(max)%(max-min+1) + min;
		String  verifyCode=dicts.get(checkIndex).getCode();
        return verifyCode;
	}
	/**
	 * @Description:还有正在处理的借款订单
	 * @author likun
	 * @Create Time: 2017年10月31日上午10:35:43
	 */
	public List<LoanOrder> getLoanOrderByClientId(Map<String, Object> params){
		
		return  loanOrderMapper.getLoanOrderByClientId(params);
	}
	
	/**
	 * @Description:借款订单申请(校验：被拒40天之后才能申请)
	 * @author likun
	 * @Create Time: 2017年10月31日上午10:35:43
	 */
	public List<LoanOrder> getRefuseLoanOrderByClientId(Map<String, Object> params){
		
		return  loanOrderMapper.getRefuseLoanOrderByClientId(params);
	}
	/**
	 * @Description:借款管理-借款订单列表-审核
	 * @author likun
	 * @Create Time: 2017年10月31日上午10:35:43
	 */
	public int checkLoanOrder(LoanOrder loanOrder, Long userId) {
		/**更新借款订单*/
		LoanOrder  newLoanOrder=new LoanOrder();
		newLoanOrder.setId(loanOrder.getId());
		newLoanOrder.setStatus(loanOrder.getStatus());
		super.update(newLoanOrder);
		
		/**订单操作日志*/
		if (1==loanOrder.getStatus()) {
			orderLogService.insertOrderLog(userId,loanOrder.getId(),1,"审核拒绝");
		} else if (2==loanOrder.getStatus()) {
			orderLogService.insertOrderLog(userId,loanOrder.getId(),1,"审核通过");
		}
		return 1;
	}
	
	/**
	 * @Description:借款管理-放款订单列表
	 * @author likun
	 * @Create Time: 2017年10月31日上午10:35:43
	 */
	public Page<LoanOrder> pageLendingOrder(LoanOrder entity) {
		long count = loanOrderMapper.getLendingOrderCount(entity);
		Page<LoanOrder> page = new Page<LoanOrder>(entity.getPageIndex_(), entity.getPageSize_());
		page.setData(loanOrderMapper.getLendingOrderList(entity));
		page.setTotalCount(count);
		return page;
	}
	
	/**
	 * @Description:借款管理-放款订单列表-放款
	 * @author likun
	 * @Create Time: 2017年10月31日上午10:35:43
	 */
	public int doLending(LoanOrder loanOrder, Long userId) {
		/**放款信息*/
		LoanOrder queryLOrder=new LoanOrder();
		queryLOrder.setId(loanOrder.getId());
		LoanOrder  loanOrderData=loanOrderMapper.getLoanOrderInfo(queryLOrder);
		
		Map<String, Object> payResultMap = new HashMap<String, Object>();
		try {
			      LOGGER.info("==============借款管理-放款订单列表-放款=============");
//			       payResultMap=payForService.handlePayment(loanOrderData);
//				   String code=(String) payResultMap.get("resultCode");
//				   if("3000".equals(code)){
			      
					    OffsetDateTime  loanTime=OffsetDateTime.now();//放款时间
					    loanOrderData.setLoanTime(loanTime);
						Integer loanTerm=loanOrderData.getLoanTerm();//借款期限
						OffsetDateTime  expirationTime=loanTime.plusDays(loanTerm.longValue());//到期时间
						loanOrderData.setExpirationTime(expirationTime);
					    /**修改借款订单*/
						updateLoanOrderByDoLending(loanOrderData);
						/**生成还款记录*/
						insertRepayOrderByDoLending(loanOrderData);
						/**交易记录*/
						insertRepayDetailByDoLending(loanOrderData, payResultMap,1);
						try {
							/**放款短信*/
							loanSendSMS(loanOrderData, userId);
						} catch (Exception e) {
							
						}
						/**订单操作日志*/
						orderLogService.insertOrderLog(userId,loanOrder.getId(),1,"放款成功");
						return 1;
//				   }else{
//					   /**交易记录*/
//					  insertRepayDetailByDoLending(loanOrderData, payResultMap,2);
//					   /**订单操作日志*/
//					  orderLogService.insertOrderLog(userId,loanOrder.getId(),1,"放款失败，请查看交易记录");
//					  return 2;
//				   }
		     
          } catch (Exception e) {
        	  e.printStackTrace();
        	  return 2;
		   }
		
	}
	/**
	 * @Description:修改借款订单
	 */
	private  void updateLoanOrderByDoLending(LoanOrder loanOrderData){
		/**修改借款订单*/
		LoanOrder  newLoanOrder=new LoanOrder();
		newLoanOrder.setId(loanOrderData.getId());
		newLoanOrder.setStatus(3);//已放款(放款中)
		newLoanOrder.setLoanTime(loanOrderData.getLoanTime());//放款时间
		newLoanOrder.setExpirationTime(loanOrderData.getExpirationTime());//到期时间
		newLoanOrder.setPaymentTime(OffsetDateTime.now());//到账时间
		super.update(newLoanOrder);
		
	}
	/**
	 * @Description:生成还款订单
	 */
	private  void  insertRepayOrderByDoLending(LoanOrder loanOrderData){
		/**生成还款订单*/
		RepayOrder repayOrder=new RepayOrder();
		repayOrder.setLoanOrderId(loanOrderData.getId());
		repayOrder.setRepayAmount(loanOrderData.getLoanAmount());
		repayOrder.setOverdueRate(loanOrderData.getOverdueRate());//逾期利率
		repayOrder.setIsOverdue(0);//初始化：未逾期
		repayOrder.setStatus(0);//初始化：未还款
		repayOrder.setBorrowTime(loanOrderData.getCreateTime());//借款时间
		repayOrder.setExpirationTime(loanOrderData.getExpirationTime());//到期时间
		repayOrder.setCreateTime(OffsetDateTime.now());//创建时间
		repayOrderMapper.insert(repayOrder);
	}
	
	/**
	 * @Description:记录交易记录
	 */
	private  void  insertRepayDetailByDoLending(LoanOrder loanOrderData,Map<String, Object> payResultMap,int type){
		/**生成放款流水记录*/
		String serialNumber=(String) payResultMap.get("serialNumber");
		String  request=(String) payResultMap.get("request");
		String  response=(String) payResultMap.get("response");
		RepayDetail repayDetail=new RepayDetail();
		repayDetail.setOrderId(loanOrderData.getId());
		repayDetail.setOrderType(1);
		repayDetail.setAmount(loanOrderData.getActualAmount());//交易金额
		repayDetail.setRepayType(type);//1放款成功，2放款失败
		repayDetail.setCreateTime(OffsetDateTime.now());
		repayDetail.setBank(loanOrderData.getBank());
		repayDetail.setCardNo(loanOrderData.getCardNo());
		repayDetail.setSerialNumber(serialNumber);//交易流水号
		repayDetail.setRequestBody(request);//交易请求
		repayDetail.setResponseBody(response);//交易响应
		repayDetail.setRemark("放款");
		repayDetailMapper.insert(repayDetail);
	}
	
	/**
	 * @Description:借款管理-放款订单列表-放款回调
	 * @author likun
	 * @Create Time: 2017年10月31日上午10:35:43
	 */
	public int doLendingCallBack(LoanOrder loanOrder) {
		LOGGER.info("==============放款回调doLendingCallBack开始==============");
		/**修改借款订单*/
		LoanOrder  loanOrderData  =loanOrderMapper.getLoanOrderInfo(loanOrder);
		long  orderId=loanOrderData.getId();
		LoanOrder  newLoanOrder=new LoanOrder();
		newLoanOrder.setId(orderId);
		newLoanOrder.setStatus(4);//已到账
		newLoanOrder.setPaymentTime(OffsetDateTime.now());//到账时间
		super.update(newLoanOrder);
		
		LOGGER.info("==============放款回调doLendingCallBack结束==============");
		return 1;
	}
	/**
	 * @Description:我的借款订单列表
	 * @author likun
	 * @Create Time: 2017年10月31日上午10:35:43
	 */
	public Page<LoanOrder> pageMyLoanOrder(LoanOrder entity) {
		long count = loanOrderMapper.getMyLoanOrderCount(entity);
		Page<LoanOrder> page = new Page<LoanOrder>(entity.getPageIndex_(), entity.getPageSize_());
		page.setData(loanOrderMapper.getMyLoanOrderList(entity));
		page.setTotalCount(count);
		return page;
	}
	public LoanOrder getLoanOrderDetail(Long id) {
		
		return loanOrderMapper.getLoanOrderDetail(id);
	}
	
	/**
	 * @Description:放款短信
	 */
	private  void  loanSendSMS(LoanOrder loanOrder,Long userId) {
		/**放款短信*/
		Map<String, String> params = dictService.getSmsDataConfig(0);
		StringBuilder content=new StringBuilder();
		
		String  cardNo=loanOrder.getCardNo();
		cardNo=cardNo.substring(cardNo.length()-4, cardNo.length());
		content=content.append(cardNo);
		try {
			params.put("content",   URLEncoder.encode(content.toString(),"utf-8"));
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		}
		params.put("mobile", loanOrder.getPhone());
	    params.put("templateId", "2812");  
		//参数：0 表示该短信为接口短信
	    SmsCodeUtil.sendSmsCode(params);
		/**订单操作日志*/
		orderLogService.insertOrderLog(userId,loanOrder.getId(),1,"发送放款短信:"+content);
	}
	
	
	 /**
     * @Description:借款管理-借款订单列表-备注
     */
	public int loanRemark(LoanOrder loanOrder , Long userId) {
		/**更新借款订单备注*/
		LoanOrder  newLoanOrder =new LoanOrder();
		newLoanOrder.setId(loanOrder.getId());
		newLoanOrder.setRemark(loanOrder.getRemark());
		loanOrderMapper.update(newLoanOrder);
		/**订单操作日志*/
		orderLogService.insertOrderLog(userId,loanOrder.getId(),1,"借款订单备注:"+loanOrder.getRemark());
		return 1;
	}
	
}
